package com.leyou.auth.service;

import com.leyou.auth.config.JwtProperties;
import com.leyou.client.UserClient;
import com.leyou.common.auth.entity.Payload;
import com.leyou.common.auth.utils.JwtUtils;
import com.leyou.common.auth.utils.UserInfo;
import com.leyou.common.enums.ExceptionEnum;
import com.leyou.common.exception.LyException;
import com.leyou.common.utils.CookieUtils;
import com.leyou.user.dto.UserDTO;
import org.joda.time.DateTime;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Date;
import java.util.concurrent.TimeUnit;

@Service
public class AuthService {

    @Autowired
    private UserClient userClient;

    @Autowired
    private JwtProperties prop;

    @Autowired
    private StringRedisTemplate redisTemplate;

    private static final String USER_ROLE = "role_user";  //假数据用于后期整权限

    public void login(String username, String password,HttpServletResponse response) {
        try{
            // 查询用户
            UserDTO userDTO = userClient.findUserInfo(username, password);
            if(userDTO==null){
                throw new LyException(ExceptionEnum.UNAUTHORIZED);
            }
            // 生成userInfo, 没写权限功能，暂时都用guest
            UserInfo userInfo = new UserInfo(userDTO.getId(),userDTO.getUsername(),USER_ROLE);
            // 生成token
            String token = JwtUtils.generateTokenExpireInMinutes(userInfo, prop.getPrivateKey(), prop.getUser().getExpire());
            // 写入cookie
            new CookieUtils.CookieBuilder()
                    .response(response)  // response,用于写cookie
                    .domain(prop.getUser().getCookieDomain())  // 设置domain,也就是域名
                    .httpOnly(true)   // 保证安全防止XSS攻击，不允许JS操作cookie
                    .name(prop.getUser().getCookieName()) // 设置cookie名称
                    .value(token)
                    .build();

        }catch (Exception e) {
            throw new LyException(ExceptionEnum.INVALID_USERNAME_PASSWORD);
        }
    }

    //给页面返回登录信息
    public UserInfo verifyUser(HttpServletRequest request, HttpServletResponse response) {
        try{
            // 读取cookie
            String token = CookieUtils.getCookieValue(request, prop.getUser().getCookieName());
            // 获取token信息,用token获取用户信息也就是解析里面的user
            Payload<UserInfo> payLoad = JwtUtils.getInfoFromToken(token, prop.getPublicKey(), UserInfo.class);

            //校验cookie是否在黑名单
            String id = payLoad.getId();
            Boolean boo = redisTemplate.hasKey(id);
            if (boo != null && boo) {
                //抛出异常停止
                throw new LyException(ExceptionEnum.UNAUTHORIZED);
            }

            //-------------------------------------
            //这样就保证用户在操作是cookie一直不过期
            // 获取过期时间
            Date expiration = payLoad.getExpiration();
            // 获取刷新时间
            DateTime refreshTime = new DateTime(expiration.getTime()).minusMinutes(prop.getUser().getMinRefreshInterval());
            // 判断是否已经过了刷新时间,  也就是需要刷新的时间在当前时间以前就刷新
            if (refreshTime.isBefore(System.currentTimeMillis())) {
                token = JwtUtils.generateTokenExpireInMinutes(payLoad.getUserInfo(), prop.getPrivateKey(), prop.getUser().getExpire());
                // 写入cookie
                new CookieUtils.CookieBuilder()
                        .response(response)  // response,用于写cookie
                        .domain(prop.getUser().getCookieDomain())  // 设置domain,也就是域名
                        .httpOnly(true)   // 保证安全防止XSS攻击，不允许JS操作cookie
                        .name(prop.getUser().getCookieName()) // 设置cookie名称
                        .value(token)
                        .build();
            }

            return payLoad.getUserInfo();
        } catch (Exception e) {
            // 抛出异常，证明token无效，直接返回401
            throw new LyException(ExceptionEnum.UNAUTHORIZED);
        }
    }

    public void logout(HttpServletRequest request, HttpServletResponse response) {
        // 获取token
        String token = CookieUtils.getCookieValue(request, prop.getUser().getCookieName());
        // 解析token
        Payload<Object> payload = JwtUtils.getInfoFromToken(token, prop.getPublicKey());
        // 获取id和有效期剩余时长,  id是为了到时候对应着id取,时长是定义redis存的时间
        String id = payload.getId();
        Long time = payload.getExpiration().getTime()-System.currentTimeMillis();

        // 写入redis, 剩余时间超过5秒以上才写
        if (time > 5000) {
            redisTemplate.opsForValue().set(id, "1", time, TimeUnit.MILLISECONDS);
        }

        // 删除cookie
        CookieUtils.deleteCookie(prop.getUser().getCookieName(), prop.getUser().getCookieDomain(), response);

    }
}
